package com.tt.aile.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tt.aile.common.pojo.PageResult;
import com.tt.aile.item.mapper.BrandMapper;
import com.tt.aile.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.management.MXBean;
import javax.sql.DataSource;
import java.util.List;

/**
 * @author 86176 shkstrat
 * @date 2020/9/21 - 21:23
 *  * key,
 *  * page,
 *  * rows,
 *  * sortBy,//排序字段
 *  * desc
 */
@Service
public class BrandService {

    @Autowired
    BrandMapper brandMapper;

    public PageResult<Brand> queryBrandByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {

        //初始化Example对象
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();

        //添加模糊查询
        if (StringUtils.isNotBlank(key)){

            criteria.andLike("name","%"+key+"%").orEqualTo("letter",key);
        }

        //添加分页
        PageHelper.startPage(page,rows);

        //添加排序
        if (StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+(desc ? " desc":" asc"));
        }

        List<Brand> brands = this.brandMapper.selectByExample(example);

        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }

    @Transactional
    public void saveBrand(Brand brand,List<Long> cids) {

        this.brandMapper.insertSelective(brand);
        for (Long cid:cids){
            this.brandMapper.insertCategoryBrand(cid,brand.getId());
        }

    }


    public List<Brand> queryBrandByCid(Long cid) {

        List<Brand> brands = this.brandMapper.queryBrandByCid(cid);

        return brands;

    }

    public Brand queryBrandById(Long id) {

        return this.brandMapper.selectByPrimaryKey(id);
    }
}
